package com.luoye.lj.platform.service.impl;

import com.luoye.lj.platform.constant.ServiceExceptionConstants;
import com.luoye.lj.platform.dao.IAuthServiceDao;
import com.luoye.lj.platform.model.domain.AuthInfo;
import com.luoye.lj.platform.model.domain.AuthInfoDetailCollection;
import com.luoye.lj.platform.model.domain.AuthInfoSearchCondition;
import com.luoye.lj.platform.model.enums.DeleteMark;
import com.luoye.lj.platform.service.IAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by wei on 2015/11/30.
 */
@Service
public class AuthServiceImpl implements IAuthService {
   // private static Logger logger = Logger.getLogger(AuthServiceImpl.class);

    @Autowired
    private IAuthServiceDao dao;

    @Transactional
    @Override
    public AuthInfo addAuth(AuthInfo aif) {
        if(StringUtils.isEmpty(aif.getAuthname())){
            throw ServiceExceptionConstants.AUTH_ALREADY_AUTHNAME;
        }
        AuthInfo role = dao.getByname(aif.getAuthname());
        System.err.println(role);
        //System.out.println(dao.getDelmark(role.getId()));
        if(role == null) {
            dao.addAuth(aif);
        }else if(DeleteMark.DELETED.getCode() == dao.getDelmark(role.getId())){
            aif.setId(role.getId());
            dao.modifyAuth(aif);
            dao.recover(role.getId());
        }else{
            throw ServiceExceptionConstants.AUTH_ALREADY_EXIST;
        }
        return aif;
    }


    @Override
    public boolean delAuth(long authId) {
        return dao.delAuth(authId);
    }

    @Override
    public AuthInfo modifyAuth(AuthInfo aif) {
        if(dao.getDelmark(aif.getId()) == DeleteMark.DELETED.getCode()){
            throw ServiceExceptionConstants.AUTH_ALREADY_NULL;
        }
        if(0 > aif.getId()){
            throw ServiceExceptionConstants.AUTH_ALREADY_NULLID;
        }
        if(StringUtils.isEmpty(aif.getAuthname())){
            throw ServiceExceptionConstants.AUTH_ALREADY_AUTHNAME;
        }
        AuthInfo reauth = dao.getById(aif.getId());
        if (!(reauth.getAuthname().equals(aif.getAuthname()))) {//如果名字和原来的不相等
            AuthInfo newauth = dao.getByname(aif.getAuthname());
            if(newauth != null ){//判断是否名字是否被占用 如果被占用抛出错误
                throw ServiceExceptionConstants.AUTH_ALREADY_REPEAT;
            }
        }
        dao.modifyAuth(aif);
        return aif;
    }

    @Override
    public List<AuthInfo> getAll() {

        return dao.getAll();
    }

    @Override
    public AuthInfo getById(long id) {

        return dao.getById(id);
    }

    @Override
    public AuthInfoDetailCollection search(AuthInfoSearchCondition authsearch) {
        return dao.search(authsearch);
    }
}
